package cn.lili.modules.grab.dingdong.service.impl;

import cn.lili.common.enums.SwitchEnum;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.DateUtil;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.grab.GrabGoodsParam;
import cn.lili.modules.grab.aop.request.RequestLogAnntion;
import cn.lili.modules.grab.aop.respose.ResponseLogAnntion;
import cn.lili.modules.grab.dingdong.reps.order.GetOrderInfoRespose;
import cn.lili.modules.grab.dingdong.res.goods.DetailRequest;
import cn.lili.modules.grab.dingdong.res.goods.GoodsQueryRequest;
import cn.lili.modules.grab.dingdong.res.notice.GoodsCallbackRequest;
import cn.lili.modules.grab.dingdong.base.BaseResult;
import cn.lili.modules.grab.dingdong.res.notice.OrderCallbackRequest;
import cn.lili.modules.grab.dingdong.res.order.GetOrderInfoRequest;
import cn.lili.modules.grab.dingdong.service.DingdongAbsService;
import cn.lili.modules.grab.dingdong.service.DingdongNoticeService;
import cn.lili.modules.grab.dingdong.service.DingdongOrderService;
import cn.lili.modules.grab.enums.SourceEnums;
import cn.lili.modules.grab.enums.StatusEnums;
import cn.lili.modules.grab.factory.goods.GrabGoodsFactory;
import cn.lili.modules.grab.factory.goods.GrabGoodsService;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.client.OrderItemClient;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.dto.OrderMessage;
import cn.lili.modules.order.order.entity.enums.DeliverStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderComplaintStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderItemAfterSaleStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.system.client.LogisticsClient;
import cn.lili.modules.system.constants.RequestLogTypeConstant;
import cn.lili.modules.system.entity.dos.Logistics;
import cn.lili.routing.GoodsRoutingKey;
import cn.lili.routing.OrderRoutingKey;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qcloud.cos.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DingdongNoticeServiceImpl extends DingdongAbsService implements DingdongNoticeService {

    @Resource
    private GoodsService goodsService;
    @Resource
    private GrabGoodsFactory grabGoodsFactory;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private AmqpExchangeProperties amqpExchangeProperties;
    @Resource
    private GoodsSkuService goodsSkuService;
    @Resource
    private OrderClient orderClient;
    @Resource
    private LogisticsClient logisticsClient;
    @Resource
    private DingdongOrderService dingdongOrderService;
    @Resource
    private OrderItemClient orderItemClient;

    /**
     * 订单回调通知接口
     *
     * @param orderCallbackRequest 通知参数
     */
    @Override
    //@ResponseLogAnntion(type = RequestLogTypeConstant.QI_DING_DONG_CREATE_ORDER_CALLBACK,typeName = RequestLogTypeConstant.QI_DING_DONG_CREATE_ORDER_CALLBACK_NAME)
    public BaseResult orderCallback(OrderCallbackRequest orderCallbackRequest) {
        log.info("企叮咚----订单回调通知明文----{}", JSONObject.toJSONString(orderCallbackRequest));
        //解密
        //已发货  0已支付 3配货中 1已发货 4已完成 9已关闭
        if ("1".equals(orderCallbackRequest.getFahuo_status())) {
            Logistics logistics;
            //根据名字查询快递公司
            logistics = logisticsClient.getByName(orderCallbackRequest.getShip_name());
            //没有查询到就插入一个
            if (logistics == null) {
                logistics = new Logistics();
                logistics.setCode("ZTO");
                logistics.setDisabled(SwitchEnum.OPEN.name());
                logistics.setName(orderCallbackRequest.getShip_name());
                logistics.setStandBy("true");
                String id = logisticsClient.save(logistics);
                logistics.setId(id);
            }

            //订单发货
            String shipSn = orderCallbackRequest.getShip_sn()[0];
            OrderItem orderItem = orderItemClient.getByIdVal(orderCallbackRequest.getOrder_sn());
            orderClient.delivery(orderItem.getOrderSn(), shipSn, logistics.getId());
        }

        //处理订单回调逻辑
        return BaseResult.builder()
                .status(StatusEnums.STATUS_200.getCode())
                .msg(StatusEnums.STATUS_200.getDes())
                .build();
    }

    /**
     * 商品信息修改通知
     *
     * @param goodsCallbackRequest 通知参数
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public BaseResult goodsCallback(GoodsCallbackRequest goodsCallbackRequest) {
        log.info("企叮咚----商品修改回调通知明文----{}", JSONObject.toJSONString(goodsCallbackRequest));
        //处理商品回调逻辑
        //查询商品
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getThirdPartyPlatformId, goodsCallbackRequest.getData().getGoods_id());
        List<Goods> goodsList = goodsService.getBaseMapper().selectList(queryWrapper);
        //下架
        if("1".equals(goodsCallbackRequest.getType()) && "0".equals(goodsCallbackRequest.getData().getUp_data())){
            for (Goods goods : goodsList) {
                goods.setMarketEnable("DOWN");
                goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
                goodsService.getBaseMapper().updateById(goods);

                //下架sku
                List<GoodsSku> skuList = goodsSkuService.getGoodsSkuListByGoodsId(goods.getId());
                skuList.forEach(e->{
                    e.setMarketEnable("DOWN");
                    e.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
                    goodsSkuService.getBaseMapper().updateById(e);
                });
            }

        }else{
            for (Goods goods : goodsList) {
                //重新拉取商品
                GrabGoodsParam grabParam = new GrabGoodsParam();
                grabParam.setStoreId(goods.getStoreId());
                grabParam.setFlag(false);
                GoodsQueryRequest goodsQueryRequest = new GoodsQueryRequest();
                goodsQueryRequest.setGoods_id(goodsCallbackRequest.getData().getGoods_id());
                grabParam.setGoodsQueryRequest(goodsQueryRequest);
                grabParam.setDetailRequest(new DetailRequest());
                grabParam.setCode(SourceEnums.DINGDONG_GOODS.name());
                grabGoodsFactory.generateGoodsFactory(grabParam);
            }
        }

        List<String> goodIds = goodsList.stream().map(Goods::getId).collect(Collectors.toList());
        // 发送删除es商品的信息
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent
                .builder()
                .source("商品删除")
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GoodsRoutingKey.GOODS_DELETE)
                .message(goodIds)
                .build());

        return BaseResult.builder()
                .status(StatusEnums.STATUS_200.getCode())
                .msg(StatusEnums.STATUS_200.getDes())
                .build();
    }
}
